/**
 * Copyright (C) 2012 The SkyTvOS Project
 *
 * Version     Date           Author
 * ─────────────────────────────────────
 *           2015-2-14         yellowlgx
 *
 */

package com.skyworth.ui.menu;

import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;

import com.skyworth.commen.ui.R;
import com.skyworth.ui.api.SkyViewConfig;
import com.skyworth.ui.define.SkyTextSize;
import com.skyworth.util.MyFocusFrame;
import com.skyworth.util.SkyScreenParams;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SkyCommenMenu
 * @Description TODO (write something)
 * @author yellowlgx
 * @date 2015-2-14
 * @version TODO (write something)
 */
public class SkySecondMenu extends FrameLayout
{
    private Context mContext;
    private int menuWidth = SkyScreenParams.getInstence(mContext).getResolutionValue(270),
            menuHeight = SkyScreenParams.getInstence(mContext).getResolutionValue(630);
    private int itemHeight = SkyScreenParams.getInstence(mContext).getResolutionValue(90);
    private int itemMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(0);

    private List<SkyMenuItem_2> menuItems;
    private SkyMenuAdapter mAdapter;
    private int dataCount = 0;

    private int lastFocusItemID = -1;

    private boolean isAnimStart = false;

    public boolean isDismisAnimStart = false;

    public boolean show_disAnimStart = false;

    public static int preViewWidth = 0;

    private int startOffset = 160;

    private int moveDuration = 100;

    private long onKeyTime = 0;

    public boolean dismissBySecondLeft_back = false;

    private FrameLayout.LayoutParams contentParams;

    private OnSecondMenuItemOnkeyListener mListener;

    private MyFocusFrame menuFocusView;

    public interface OnSecondMenuItemOnkeyListener
    {
        public boolean onSecondMenuItemOnKeyLeft(int itemID, View v);

        public boolean onSecondMenuItemOnKeyRight(int itemID, View v, SkyMenuData currentData);

        public boolean onSecondMenuItemOnClick(int itemIndex, View v, SkyMenuData currentData);

        public boolean onSecondMenuItemOnKeyBack(int itemID, View v);

        public boolean onSecondMenuOnKeyOther(int itemID, View v, int keyCode);
    }

    private OnSecondItemAnimListener mAnimListener;

    public interface OnSecondItemAnimListener
    {
        public void onSecondItemAnimEnd(boolean isShow);
    }

    public SkySecondMenu(Context context)
    {
        super(context);
        mContext = context;
        initView();
        this.setFocusable(false);
    }

    public void setSecondMenuOnItemOnkeyListener(OnSecondMenuItemOnkeyListener listener)
    {
        mListener = listener;
    }

    public void setOnSecondItemAnimListener(OnSecondItemAnimListener listener)
    {
        mAnimListener = listener;
    }

    public void setFocusView(MyFocusFrame menuFocusView)
    {
        this.menuFocusView = menuFocusView;
    }

    private void initView()
    {
        menuItems = new ArrayList<SkyMenuItem_2>();
        contentParams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, menuHeight);
        this.setLayoutParams(contentParams);
    }

    public void setPreViewWidth(int width)
    {
        preViewWidth = width;
    }

    public void refreshItemData(SkyMenuData data, int index)
    {
        if (menuItems != null && menuItems.size() >= index)
        {
            menuItems.get(index).refreshItemValue(data);
        }
    }

    public void setMenuItemFocus(int id)
    {
        if (id > 0)
        {
            if (menuItems != null && id < menuItems.size() && menuItems.get(id) != null)
            {
                boolean focus = menuItems.get(id).requestFocus();
                Log.v("lgx", "focus == " + focus);
            }
        }
    }
    
    public void refreshOnThemeChanged()
    {
        if (menuItems != null)
        {
            for (int i = 0; i < menuItems.size(); i++)
            {
                menuItems.get(i).refreshOnThemeChanged();
            }
        }
    }

    public void setMenuAdapter(final SkyFirstMenu menu1, SkyMenuAdapter adapter, final int focuseID)
    {
        this.removeAllViews();

        lastFocusItemID = -1;
        isAnimStart = false;
        isDismisAnimStart = false;
        dismissBySecondLeft_back = false;

        if (menuItems != null)
            menuItems.clear();
        if (mAdapter != null)
            mAdapter = null;
        dataCount = 0;

        mAdapter = adapter;
        if (mAdapter != null)
        {
            dataCount = mAdapter.getCount();
            if (dataCount <= 0)
            {
                return;
            }
            FrameLayout.LayoutParams itemParams = null;
            for (int i = 0; i < dataCount; i++)
            {
                SkyMenuItem_2 item = new SkyMenuItem_2(mContext);
                item.setTextAttribute(
                        SkyScreenParams.getInstence(mContext).getTextDpiValue(SkyTextSize.t_4),
                        R.color.c_4);
                item.setFocusView(menuFocusView);
                item.setId(i);
                item.setSelectState(false);
                item.setOnKeyListener(itemOnKeyListener);
                // item.setOnClickListener(itemClickListener);
                item.setOnTouchListener(touchListener);
                item.updataItemValue(mAdapter.getMenuItemData(i));
                itemParams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, itemHeight);
                itemParams.topMargin = (i + 3 - focuseID) * (itemHeight + itemMargin);
                if (itemParams != null)
                    item.setLayoutParams(itemParams);
                menuItems.add(item);
                this.addView(item);
                item.setVisibility(View.INVISIBLE);
            }
            if (this.getVisibility() != View.VISIBLE)
            {
                this.setVisibility(View.VISIBLE);
                show_dismissAnimation(menu1, true, focuseID, false);
            } else
            {
                if (menuItems != null && (menuItems.size() - 1) >= focuseID)
                {
                    menuItems.get(focuseID).post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            menuItems.get(focuseID).setSelectState(true);
                            menuItems.get(focuseID).requestFocus();
                            menu1.setItemFocusble(true, 0, false);
                            menu1.setShowingSecondMenu(false);
                        }
                    });
                }
            }
        }
    }

    public void show_dismissAnimation(final SkyFirstMenu menu1, final boolean isShow,
            final int index, final boolean needRecoll)
    {
        show_disAnimStart = true;
        this.post(new Runnable()
        {
            @Override
            public void run()
            {
                int midleIndex = 0;
                int start = 0, end = 0;
                if ((index - 3) >= 0)
                {
                    start = index - 3;
                } else
                {
                    start = 0;
                }
                if ((index + 3) <= (menuItems.size() - 1))
                {
                    end = index + 4;
                } else
                {
                    end = menuItems.size();
                }
                List<SkyMenuItem_2> targetItems = menuItems.subList(start, end);
                TranslateAnimation transAnimation = null;
                AlphaAnimation alphInAnimation = null;
                if (targetItems != null)
                {
                    final int count = targetItems.size();
                    if (count == 7)
                    {
                        midleIndex = 3;
                    } else if (count < 7)
                    {
                        if (index < 3)
                            midleIndex = index;
                        else
                            midleIndex = 3;
                    }
                    for (int i = 0; i < count; i++)
                    {
                        // targetItems.get(i).clearAnimation();
                        AnimationSet animset = new AnimationSet(false);
                        if (isShow)
                        {
                            animset.setFillAfter(false);
                            transAnimation = new TranslateAnimation(-SkySecondMenu.this.getWidth(),
                                    0, 0, 0);
                            alphInAnimation = new AlphaAnimation(0.2f, 1);
                            transAnimation.setInterpolator(new AccelerateInterpolator());
                            alphInAnimation.setInterpolator(new AccelerateInterpolator());
                        } else
                        {
                            animset.setFillAfter(true);
                            transAnimation = new TranslateAnimation(0,
                                    -SkySecondMenu.this.getWidth(), 0, 0);
                            alphInAnimation = new AlphaAnimation(1, 0);
                            transAnimation.setInterpolator(new DecelerateInterpolator());
                            alphInAnimation.setInterpolator(new DecelerateInterpolator());
                        }
                        transAnimation.setStartOffset(((i) * 50) / count);
                        transAnimation.setDuration(100);
                        animset.addAnimation(transAnimation);

                        alphInAnimation.setStartOffset(((i) * 50) / count);
                        alphInAnimation.setDuration(100);
                        animset.addAnimation(alphInAnimation);
                        if (i == midleIndex)
                        {
                            animset.setAnimationListener(new AnimationListener()
                            {
                                @Override
                                public void onAnimationStart(Animation animation)
                                {
                                    if (index == (dataCount - 1))
                                    {
                                        if (mAnimListener != null && needRecoll)
                                            mAnimListener.onSecondItemAnimEnd(isShow);
                                    }
                                    if (!isShow)
                                    {
                                        // if (menu1 != null)
                                        // menu1.setMenuItemFocus(menu1.getLastFocusID());
                                    } else if (isShow)
                                    {
                                        if (menuItems != null && (menuItems.size() - 1) >= index)
                                        {
                                            menuItems.get(index).setSelectState(true);
                                            menuItems.get(index).requestFocus();
                                            int[] location = new int[2];
                                            menuItems.get(index).getLocationInWindow(location);
                                            int shaderSize = SkyScreenParams.getInstence(mContext)
                                                    .getResolutionValue(SkyViewConfig.FOCUS_VIEW_SHADER_OFFSET);
                                            int x = location[0] - shaderSize;
                                            int y = location[1] - shaderSize;
                                            int width = SkyScreenParams.getInstence(mContext)
                                                    .getResolutionValue(344) + shaderSize * 2;
                                            int height = SkyScreenParams.getInstence(mContext)
                                                    .getResolutionValue(90) + shaderSize * 2;

                                            menuFocusView.changeFocusPos(x, y, width, height);
                                            menu1.setItemFocusble(true, 0, false);
                                            menu1.setShowingSecondMenu(false);
                                        }
                                    }
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation)
                                {
                                }

                                @Override
                                public void onAnimationEnd(Animation animation)
                                {
                                    if (index == (dataCount - 1))
                                    {
                                        show_disAnimStart = false;
                                        if (!isShow)
                                        {
                                            SkySecondMenu.this.setVisibility(View.INVISIBLE);
                                            isDismisAnimStart = false;
                                        }
                                    }
                                }
                            });
                        }

                        if (i == (count - 1) && index != (dataCount - 1))
                        {
                            animset.setAnimationListener(new AnimationListener()
                            {
                                @Override
                                public void onAnimationStart(Animation animation)
                                {
                                    if (mAnimListener != null && needRecoll)
                                        mAnimListener.onSecondItemAnimEnd(isShow);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation)
                                {
                                }

                                @Override
                                public void onAnimationEnd(Animation animation)
                                {
                                    show_disAnimStart = false;
                                    if (!isShow)
                                    {
                                        SkySecondMenu.this.setVisibility(View.INVISIBLE);
                                        isDismisAnimStart = false;
                                    }
                                }
                            });
                        }

                        targetItems.get(i).setVisibility(View.VISIBLE);
                        targetItems.get(i).startAnimation(animset);
                    }
                }
            }
        });
    }

    // OnClickListener itemClickListener = new OnClickListener()
    // {
    // @Override
    // public void onClick(View v)
    // {
    // if (isAnimStart)
    // {
    // return;
    // }
    //
    // for (int i = 0; i < dataCount; i++)
    // {
    // if (v.getId() != i)
    // {
    // menuItems.get(i).setSelectState(false);
    // menuItems.get(i).reSetItemState();
    // }
    // }
    // ((SkyMenuItem_2) v).setSelectState(true);
    // if (mListener != null)
    // mListener.onSecondMenuItemOnClick(v.getId(), v, ((SkyMenuItem_2) v).getItemData());
    // }
    // };

    OnTouchListener touchListener = new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                if (isAnimStart)
                {
                    return true;
                }

                for (int i = 0; i < dataCount; i++)
                {
                    if (v.getId() != i)
                    {
                        menuItems.get(i).setSelectState(false);
                        menuItems.get(i).reSetItemState();
                    }
                }
                ((SkyMenuItem_2) v).setSelectState(true);
                if (mListener != null)
                {
                    mListener.onSecondMenuItemOnClick(v.getId(), v,
                            ((SkyMenuItem_2) v).getItemData());
                    return true;
                } else
                {
                    return false;
                }
            }
            return false;
        }
    };

    public void setLastFocusItemID(int id)
    {
        lastFocusItemID = id;
    }

    public int getLastFocusID()
    {
        return lastFocusItemID;
    }

    OnKeyListener itemOnKeyListener = new OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                lastFocusItemID = -1;
                int id = v.getId();
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP)
                {
                    long upTime = System.currentTimeMillis();
                    if ((upTime - onKeyTime) < 150)
                    {
                        startOffset = 60;
                        moveDuration = 60;
                    } else
                    {
                        startOffset = 160;
                        moveDuration = 100;
                    }
                    onKeyTime = System.currentTimeMillis();
                    if (isAnimStart)
                    {
                        return true;
                    }
                    if (mListener != null)
                        mListener.onSecondMenuOnKeyOther(id, v, keyCode);
                    if (id != 0)
                    {
                        menuFocusView.needAnimtion(false);
                        onKeyItemMoveEvent(keyCode, v);
                        return true;
                    } else
                        return true;

                } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
                {
                    long downTime = System.currentTimeMillis();
                    Log.v("xw", "downTime == " + downTime);
                    Log.v("xw", "onKeyTime == " + onKeyTime);
                    Log.v("xw", "(downTime - onKeyTime) == " + (downTime - onKeyTime));
                    if ((downTime - onKeyTime) < 150)
                    {
                        startOffset = 60;
                        moveDuration = 60;
                    } else
                    {
                        startOffset = 160;
                        moveDuration = 100;
                    }
                    onKeyTime = System.currentTimeMillis();
                    if (isAnimStart)
                    {
                        return true;
                    }
                    if (mListener != null)
                        mListener.onSecondMenuOnKeyOther(id, v, keyCode);
                    if (id != dataCount - 1)
                    {
                        menuFocusView.needAnimtion(false);
                        onKeyItemMoveEvent(keyCode, v);
                        return true;
                    } else
                        return true;
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
                {
                    Log.v("xw", "isShowAnimStart == " + isDismisAnimStart);
                    if (isAnimStart)
                    {
                        return true;
                    }
                    if (mListener != null)
                    {
                        menuFocusView.needAnimtion(false);
                        return mListener.onSecondMenuItemOnKeyLeft(id, v);
                    } else
                    {
                        return true;
                    }
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
                {
                    if (isAnimStart)
                    {
                        return true;
                    }
                    if (mListener != null)
                    {
                        return mListener.onSecondMenuItemOnKeyRight(id, v,
                                ((SkyMenuItem_2) v).getItemData());
                    } else
                    {
                        return true;
                    }
                } else if (keyCode == KeyEvent.KEYCODE_BACK)
                {
                    if (isAnimStart)
                    {
                        return true;
                    }
                    if (mListener != null)
                    {
                        return mListener.onSecondMenuItemOnKeyBack(id, v);
                    } else
                    {
                        return false;
                    }
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
                        || keyCode == KeyEvent.KEYCODE_ENTER)
                {
                    if (isAnimStart)
                    {
                        return true;
                    }

                    for (int i = 0; i < dataCount; i++)
                    {
                        if (v.getId() != i)
                        {
                            menuItems.get(i).setSelectState(false);
                            menuItems.get(i).reSetItemState();
                        }
                    }
                    ((SkyMenuItem_2) v).setSelectState(true);
                    if (mListener != null)
                    {
                        mListener.onSecondMenuItemOnClick(v.getId(), v,
                                ((SkyMenuItem_2) v).getItemData());
                        return true;
                    } else
                    {
                        return true;
                    }

                } else
                {
                    if (mListener != null)
                    {
                        return mListener.onSecondMenuOnKeyOther(id, v, keyCode);
                    } else
                    {
                        return false;
                    }
                }
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                return true;
            }
            return false;
        }
    };

    private void onKeyItemMoveEvent(int keyCode, View v)
    {
        isAnimStart = true;
        final int index = v.getId();
        final int moveY = itemHeight + itemMargin;
        TranslateAnimation transAnimation = null;
        AlphaAnimation alphInAnimation = null;
        AlphaAnimation alphOutAnimation = null;
        AnimationSet animset = null;
        final int itemCount = mAdapter.getCount();
        // 按上键，所有Item需要往下移动
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP)
        {
            for (int i = itemCount - 1; i >= 0; i--)
            {
                final SkyMenuItem_2 item = menuItems.get(i);

                FrameLayout.LayoutParams item_p = (LayoutParams) item.getLayoutParams();
                item_p.topMargin += moveY;
                item.setLayoutParams(item_p);
                item.clearAnimation();

                animset = new AnimationSet(false);
                transAnimation = new TranslateAnimation(0, 0, -moveY, 0);
//                transAnimation.setStartOffset(((itemCount - 1 - i) * startOffset) / itemCount);
                transAnimation.setDuration(moveDuration);
                transAnimation.setInterpolator(new AccelerateInterpolator());
                animset.addAnimation(transAnimation);

                if (item.getVisibility() != View.VISIBLE)
                    item.setVisibility(View.VISIBLE);

                if (i == index - 4)
                {
                    alphInAnimation = new AlphaAnimation(0, 1);
                    alphInAnimation.setFillAfter(true);
                    alphInAnimation.setDuration(moveDuration);
//                    alphInAnimation.setStartOffset((i * startOffset) / itemCount);
                    animset.addAnimation(alphInAnimation);
                }

                if (i == index + 3)
                {
                    alphOutAnimation = new AlphaAnimation(1, 0);
                    alphOutAnimation.setFillAfter(true);
                    alphOutAnimation.setDuration(moveDuration);
//                    alphOutAnimation
//                            .setStartOffset(((itemCount - 1 - i) * startOffset) / itemCount);
                    animset.addAnimation(alphOutAnimation);
                }
                item.startAnimation(animset);

                if (i == 0)
                {
                    transAnimation.setAnimationListener(new AnimationListener()
                    {
                        @Override
                        public void onAnimationStart(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation)
                        {
                            if ((index + 3) < itemCount && menuItems.get(index + 3) != null)
                            {
                                menuItems.get(index + 3).setVisibility(View.INVISIBLE);
                            }
                            if ((index - 1) == 0)
                            {
                                menuItems.get(index - 1).requestFocus();
                            }
                            isAnimStart = false;
                        }
                    });
                } else if (i == index - 1)
                {
                    transAnimation.setAnimationListener(new AnimationListener()
                    {
                        @Override
                        public void onAnimationStart(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation)
                        {
                            menuItems.get(index - 1).requestFocus();
                            if ((index - 1) == 0)
                            {
                                isAnimStart = false;
                            }
                        }
                    });
                }
            }
            // 按下键，所有Item需要往上移动
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
        {
            for (int i = 0; i < itemCount; i++)
            {
                final SkyMenuItem_2 item = menuItems.get(i);

                FrameLayout.LayoutParams item_p = (LayoutParams) item.getLayoutParams();
                item_p.topMargin -= moveY;
                item.setLayoutParams(item_p);
                item.clearAnimation();

                animset = new AnimationSet(false);
                transAnimation = new TranslateAnimation(0, 0, moveY, 0);
//                transAnimation.setStartOffset((i * startOffset) / itemCount);
                transAnimation.setDuration(moveDuration);
                transAnimation.setInterpolator(new AccelerateInterpolator());
                animset.addAnimation(transAnimation);

                if (item.getVisibility() != View.VISIBLE)
                    item.setVisibility(View.VISIBLE);

                if (i == index - 3)
                {
                    alphOutAnimation = new AlphaAnimation(1, 0);
                    alphOutAnimation.setFillAfter(true);
                    alphOutAnimation.setDuration(moveDuration);
//                    alphOutAnimation.setStartOffset((i * startOffset) / itemCount);
                    animset.addAnimation(alphOutAnimation);
                }

                if (i == index + 4)
                {
                    alphInAnimation = new AlphaAnimation(0, 1);
                    alphInAnimation.setFillAfter(true);
                    alphInAnimation.setDuration(moveDuration);
//                    alphInAnimation.setStartOffset(((itemCount - 1 - i) * startOffset) / itemCount);
                    animset.addAnimation(alphInAnimation);
                }

                item.startAnimation(animset);

                if (i == (itemCount - 1))
                {
                    transAnimation.setAnimationListener(new AnimationListener()
                    {
                        @Override
                        public void onAnimationStart(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation)
                        {
                            if ((index - 3) >= 0 && menuItems.get(index - 3) != null)
                            {
                                menuItems.get(index - 3).setVisibility(View.INVISIBLE);
                            }
                            if ((index + 1 == itemCount - 1))
                            {
                                menuItems.get(index + 1).requestFocus();
                            }
                            isAnimStart = false;
                        }
                    });
                } else if (i == (index + 1))
                {
                    transAnimation.setAnimationListener(new AnimationListener()
                    {
                        @Override
                        public void onAnimationStart(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation)
                        {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation)
                        {
                            menuItems.get(index + 1).requestFocus();
                        }
                    });
                }
            }
        }

    }
}
